<template>
    <div class="content">
      <div class="content-head">
        <div class="head-btns" style="margin-bottom: 20px;">
            <el-button type="primary" size="mini" icon="el-icon-arrow-left" @click="backEvent">返回</el-button>
            <el-button type="warning" size="mini" icon="el-icon-document" :loading="saveBtnLoading" @click="saveEvent">保存</el-button>
        </div>
        <el-form :inline="true" :model="formData" size="small" label-position="left" label-width="60px">
          <el-row>
            <el-col :span="24">
                <el-form-item label="单号">
                    <el-input v-model="formData.workOrderNum" disabled></el-input>
                </el-form-item>
                <el-form-item label="创建人">
                    <el-input :value="formData.username" disabled></el-input>
                </el-form-item>
                <el-form-item label="日期">
                    <el-date-picker v-model="formData.date" type="date" :disabled="isAllocated === 1" :clearable="false"></el-date-picker>
                </el-form-item>
                <el-form-item label="类型">
                    <el-select v-model="formData.type" placeholder="请选择类型">
                        <el-option label="设备修理" :value="0"></el-option>
                        <el-option label="打扫" :value="1"></el-option>
                        <el-option label="更换配件" :value="2"></el-option>
                        <el-option label="其它" :value="3"></el-option>
                    </el-select>
                </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="备注">
            <el-input type="textarea" v-model="formData.comment" autosize></el-input>
          </el-form-item>
          <el-row style="margin-top: 20px;">
            <el-col :span="24">
                <el-form-item label="分摊工时" label-width="70px">
                    <el-input placeholder="请输入" v-model="formData.workHourAllocation" @input="workHourAllocationInputEvent">
                        <template slot="append">分</template>
                    </el-input>
                </el-form-item>
            </el-col>
            <el-col :span="24">
                <el-form-item>
                    <el-button type="primary" size="mini" icon="el-icon-s-flag" @click="allocationEvent">一键分摊</el-button>
                </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="content-table">
        <div class="table-main">
          <el-popover placement="top-start" trigger="hover">
            <el-radio-group v-model="isAllocated">
                <el-radio :label="0">未分摊</el-radio>
                <el-radio :label="1">已分摊</el-radio>
            </el-radio-group>
            <!-- <el-button type="text" size="mini" @click="openDialogEvent" style="margin-left: 20px;">打开弹窗</el-button> -->
            <el-button slot="reference" size="mini">选择生产订单报工记录</el-button>
          </el-popover>
          <el-table :data="dealTableData" style="width: 100%;" border highlight-current-row :max-height="tableMaxHeight" class="content-table-item">
            <el-table-column prop="" label="序号" type="index" align="center" width="60"></el-table-column> 
            <el-table-column prop="productOrderCode" label="生产订单号" align="center" width=""></el-table-column>
            <el-table-column prop="materialCode" label="产品编号" align="center" width=""></el-table-column>
            <el-table-column prop="materialName" label="产品名称" align="center" width=""></el-table-column>
            <el-table-column prop="quantity" label="生产数量" align="center" width=""></el-table-column>
            <el-table-column prop="operatorName" label="生产人员" align="center" width=""></el-table-column>
            <el-table-column prop="productionWorkHours" label="生产工时" align="center" width=""></el-table-column>
            <el-table-column prop="allocatedWorkHours" label="辅助工时" align="center" width=""></el-table-column>
            <el-table-column prop="totalWorkHours" label="总工时" align="center" width=""></el-table-column>
            <el-table-column prop="comment" label="生产备注" align="center" width=""></el-table-column>
            <el-table-column prop="" label="操作" align="center" width="">
                <template slot-scope="{row,$index}">
                    <el-popconfirm title="确定删除吗？" @confirm="deleteEvent($index)">
                        <el-button type="text" size="mini" slot="reference">删除</el-button>
                    </el-popconfirm>
                </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <!-- dialog弹出层 -->
      <el-dialog :title="title" :visible.sync="dialogVisible" :close-on-click-modal="false" width="60%">
        <el-table :data="dialogTableData" v-loading="tableLoading" style="width: 100%;" border highlight-current-row height="400px" @select="tableHandlerSelect" @select-all="tableHandlerSelect" class="content-table-item">
            <el-table-column prop="" label="" type="selection" align="center" width="60"></el-table-column>
            <el-table-column prop="" label="序号" type="index" align="center" width="60"></el-table-column>
            <el-table-column prop="productOrderCode" label="生产订单号" align="center" width="150"></el-table-column>
            <el-table-column prop="materialCode" label="产品编号" align="center" width="150"></el-table-column>
            <el-table-column prop="materialName" label="产品名称" align="center" width="120"></el-table-column>
            <el-table-column prop="quantity" label="生产数量" align="center" width=""></el-table-column>
            <el-table-column prop="operatorName" label="生产人员" align="center" width=""></el-table-column>
            <el-table-column prop="productionWorkHours" label="生产工时" align="center" width=""></el-table-column>
            <el-table-column prop="allocatedWorkHours" label="辅助工时" align="center" width=""></el-table-column>
            <el-table-column prop="totalWorkHours" label="总工时" align="center" width=""></el-table-column>
            <el-table-column prop="comment" label="生产备注" align="center" width=""></el-table-column>
        </el-table>
        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false" size="mini">取 消</el-button>
            <el-button type="primary" @click="dialogConfirmEvent" size="mini">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import { portrait, autoOrientation, fullscreen } from "@/utils/rotatingScreen.js";
  import { reqUserInfo,reqAllocationNumber,reqProductReportRecord,reqAllocationRecord, reqSaveWorkHourAllocations, reqUpdateWorkHourAllocations } from "@/api/workHourAllocation.js";
  import M from "moment";
  import T from "@/utils/tools.js";
  import { cloneDeep } from "lodash";
  export default {
    name:"WorkHourAllocationAdd",
    data() {
      return {
        formData:{
            workOrderNum:"",
            username:"",
            date:M().format("YYYY-MM-DD"),
            type:0,
            comment:"",
            workHourAllocation:""
        },
        dialogVisible:false,
        dialogTableData:[],
        dialogSelectedList:[],
        tableData:[],
        tableLoading:false,
        exportBtnLoading:false,
        tableMaxHeight:450,
        isAllocated:null,  //选择展示的是否已分摊的(已分摊的需要进行编辑，默认未分摊[0-未分摊,1-已分摊])
        saveBtnLoading:false
      }
    },
    computed:{
        title(){
            const isAllocated = this.isAllocated;
            if(isAllocated === 0){
                return "选择未分摊数据源";
            }
            if(isAllocated === 1){
                return "选择已分摊数据源";
            }
            return "请选择";
        },
        dealTableData(){
            const isAllocated = this.isAllocated;
            if(isAllocated === 1){
                const list = this.tableData.filter(val => val.deleteRemark !== 1);
                console.log('list',list);
                return list;
            } else if(isAllocated === 0){
                return this.tableData;
            }
        }
    },
    mounted(){
        this.getAllocationNumber();
        //this.getProductReportRecord();
        this.getCurrentUserInfo();
        this.calculateTableMaxHeight();
        window.addEventListener("resize",this.calculateTableMaxHeight);
        //精致环境下进行自动旋转
        const isDevelopment = process.env.NODE_ENV === 'development';
        if(!isDevelopment){
            autoOrientation();
        }
        document.title = "工时分摊新增";
    },
    beforeDestroy(){
      window.removeEventListener("resize",this.calculateTableMaxHeight);
    },
    watch:{
        "isAllocated":{
            handler(newVal,oldVal){
                if(newVal === 1){
                    this.getAllocationRecord();
                }
                if(newVal === 0){
                    this.getAllocationNumber();
                    this.getProductReportRecord();
                    this.getCurrentUserInfo();
                }
                this.dialogVisible = true;
                this.tableData = [];
            }
        }
    },
    methods:{
        //获取当前用户信息
        getCurrentUserInfo(){
            const userInfo = T.getUserInfoByToken();
            const nickName = userInfo.given_name || userInfo.name;
            this.formData.username = nickName;
            console.log("获取用户信息",userInfo);
        },
        //一键分摊
        async allocationEvent(){
            if(!this.formData.workHourAllocation){
                this.$notify({title:"提示", message:"请先输入分摊工时",type:"warning",duration:2000});
                return ;
            }
            const totalMinutes = Number(this.formData.workHourAllocation);
            const totalHours = Number((totalMinutes / 60).toFixed(4));
            const isAllocated = this.isAllocated;
            const list = this.tableData;
            if(isAllocated === 0){
                if(list.length === 0){
                    this.$notify({title:"提示", message:"未选择任何订单报工记录",type:"warning",duration:2000});
                    return ;
                }
                await T.sleep(1000);
                const allWorkOrderNum = list.reduce((pre,cur) => pre + Number(cur.quantity),0);
                for(let i = 0 ; i < list.length; i ++){
                    const t = list[i];
                    t.allocatedWorkHours = Number((totalHours / (allWorkOrderNum > 0 ? allWorkOrderNum : 1) * Number(t.quantity)).toFixed(2));
                    t.totalWorkHours = (Number(t.productionWorkHours) + Number(t.allocatedWorkHours)).toFixed(2);
                }
            } else if (isAllocated === 1) {
                const filterList = list.filter(val => val.deleteRemark !== 1);
                if(filterList.length === 0){
                    this.$notify({title:"提示", message:"未选择任何订单报工记录",type:"warning",duration:2000});
                    return ;
                }
                await T.sleep(1000);
                const allWorkOrderNum = filterList.reduce((pre,cur) => pre + Number(cur.quantity),0);
                for(let i = 0 ; i < filterList.length; i ++){
                    const t = filterList[i];
                    t.allocatedWorkHours = Number((totalHours / (allWorkOrderNum > 0 ? allWorkOrderNum : 1) * Number(t.quantity)).toFixed(2));
                    t.totalWorkHours = (Number(t.productionWorkHours) + Number(t.allocatedWorkHours)).toFixed(2);
                }
            } else {
                this.$notify({title:"提示", message:"请先选择已分摊或者未分摊的数据源",type:"warning",duration:2000});
            }
        },
        saveEvent(){
            const isAllocated = this.isAllocated //0-未分摊 1-已分摊
            const { workOrderNum,username,date,type,comment,workHourAllocation } = this.formData;
            const list = cloneDeep(this.tableData);
            for(let j = 0; j < list.length; j ++){
                const t = list[j];
                t.allocationCode = workOrderNum;
                t.createdBy = username;
                t.allocationDate = date;
                t.allocationType = type;
                t.comment = comment;
                t.totalAssistanceHours = (Number(workHourAllocation) / 60).toFixed(2);
                t.totalWorkHours = (Number(t.productionWorkHours) + Number(t.allocatedWorkHours)).toFixed(2);
            }
            console.log("请求参数===>",list);
            let executeMethod = null;
            if(isAllocated === 0){
                executeMethod = reqSaveWorkHourAllocations;
            } else if( isAllocated === 1) {
                executeMethod = reqUpdateWorkHourAllocations;
            }
            if(list.length === 0){
                this.$notify({title:"提示", message:"未选择任何订单数据",type:"warning",duration:2000});
                return;
            }
            if(isAllocated === 0 && !list[0].allocatedWorkHours){
                this.$notify({title:"提示", message:"分摊工时不能为空",type:"error",duration:2000});
                return;
            }
            this.saveBtnLoading = true;
            executeMethod(list).then(response => {
                if(response.data.code === 200){
                    this.$notify({title:"提示", message:"保存成功",type:"success",duration:2000});
                    if(this.isAllocated === 1){
                        this.getAllocationRecord();
                    }
                    if(this.isAllocated === 0){
                        this.getAllocationNumber();
                        this.getProductReportRecord();
                        this.getCurrentUserInfo();
                    }
                    this.formData.workHourAllocation = "";
                    this.formData.comment = "";
                    this.backEvent();
                }
                console.log('保存api',response);
                this.saveBtnLoading = false;
            }, error => {
                this.$notify({title:"提示", message:"保存失败，请重试",type:"error",duration:2000});
                console.log('保存api',error);
                this.saveBtnLoading = false;
            })
        },
        deleteEvent(index){
            const isAllocated = this.isAllocated;
            if(isAllocated === 0){
                this.tableData.splice(index,1);
            } else if (isAllocated === 1){
                this.tableData[index].deleteRemark = 1;
            }
        },
        //获取订单报工记录列表
        getProductReportRecord(){
            reqProductReportRecord().then(response => {
                if(response.data.code === 200){
                    const list = response.data.data.map(val => {
                        return {
                            ...val,
                            allocatedWorkHours:"",
                            comment:"",
                            totalWorkHours:"",
                            totalAssistanceHours:""
                        }
                    });
                    this.dialogTableData = list;
                }
                console.log('获取订单报工记录列表api',response);
            }, error => {
                console.log('获取订单报工记录列表api',error);
            })
        },
        getAllocationRecord(){
            reqAllocationRecord().then(response => {
                if(response.data.code === 200){
                    const list = response.data.data;
                    if(list.length > 0){
                        const { allocationCode,createdBy,allocationDate,allocationType,comment } = list[0];
                        this.formData.workOrderNum = allocationCode;
                        this.formData.username = createdBy;
                        this.formData.date = allocationDate;
                        this.formData.type = allocationType;
                        this.formData.comment = comment;
                    }
                    this.dialogTableData = list;
                }
                console.log('获取已分摊的信息',response);
            }, error => {
                console.log('获取已分摊的信息',error);
            })
        },
        //生成分摊编号
        getAllocationNumber(){
            reqAllocationNumber().then(response => {
                if(response.data.code === 200){
                    const num = response.data.data;
                    this.formData.workOrderNum = num;
                }
                console.log('生成分摊编号api',response);
            }, error => {
                console.log('生成分摊编号api',error);
            })
        },
        calculateTableMaxHeight(){
            const dom = document.querySelector(".table-main");
            this.$nextTick(() => {
            this.tableMaxHeight = dom.offsetHeight - 10;
            })
        },
        backEvent(){
            this.$router.push({name:"WorkHourAllocation"});
        },
        workHourAllocationInputEvent(){
            const inputVal = this.formData.workHourAllocation;
            const regex = /^(?:0|[1-9]\d*)$/;
            if(!regex.test(inputVal)){
                this.formData.workHourAllocation = inputVal.slice(0,-1);
            }
        },
        tableHandlerSelect(selectedList,row){
            console.log("选择的数据:",selectedList);
            this.dialogSelectedList = cloneDeep(selectedList);
        },
        async dialogConfirmEvent(){
            const isAllocated = this.isAllocated;
            if(isAllocated === 1){
                const list = this.dialogSelectedList.map(val => val.id);
                const array = cloneDeep(this.dialogTableData);
                if(list.length === 0){
                    this.$notify({title:"提示", message:"未选择任何订单",type:"warning",duration:2000});
                    return;
                }
                this.dialogVisible = false;
                await T.sleep(500);
                array.forEach(val => {
                    if(!list.includes(val.id)){
                        val.deleteRemark = 1;
                    } else {
                        val.deleteRemark = 0;
                    }
                })
                this.tableData = array;
            } else if (isAllocated === 0){
                this.dialogVisible = false;
                await T.sleep(500);
                this.tableData = this.dialogSelectedList;
            }
        },
        openDialogEvent(){
            const isAllocated = this.isAllocated;
            if(!(isAllocated === 0 || isAllocated === 1)){
                this.$notify({title:"提示", message:"请先选择已分摊或者未分摊数据源",type:"error",duration:2000});
                return ;
            }
            if(isAllocated === 1){
                this.getAllocationRecord();
            }
            if(isAllocated === 0){
                this.getProductReportRecord();
            }
            this.dialogVisible = true;
        }
    }
  }
  </script>
  
<style lang='scss' scoped>
.content{
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 1%;
  box-sizing: border-box;
  user-select: none;

  .content-head{
    flex: 0.5;
    .form-item{
      margin-right: 2vw;
    }
  }
  .content-table{
    flex: 8;
    margin: 10px 0;
    .table-date{
      width: 100%;
      height: 2%;
      min-height: 15px;
      margin-bottom: 0.5%;
      display: flex;
      justify-content: right;
    }
    .table-main{
      width: 100%;
      height: 98%;
    }
  }
  .content-footer{
    flex: 0.5;
    display: flex;
    justify-content: flex-end;
  }
}
/*
::v-deep .el-table__header th {
  padding: 0;
}
::v-deep .el-table__row {
  margin-bottom: 15px;
}
::v-deep .el-table .el-table__cell{
  padding: 0;
}
*/
</style>